import imgHandle from '../helpers/imgHandle';
import {uploadToken} from '../config/Cache';

export default async (files, imgOptions, ajaxOptions = {}, uploadPath, drive, tokenUrl) => {
    if (ajaxOptions && !ajaxOptions.onUploadProgress) {
        ajaxOptions.onUploadProgress = (e) => {
            // console.log(parseInt((e.loaded / e.total).toFixed(2) * 100));
        };
    }

    const uploadParameter = await uploadToken(drive, tokenUrl);
    if (uploadPath) uploadPath += '/';
    if (!uploadPath) uploadPath = '';

    let filesUrl = [];
    for (let i = 0; i < files.length; i++) {
        let file = files[i];
        if (file.type.includes('image') && !file.type.includes('gif') && imgOptions) {
            const newFile = await imgHandle(file, imgOptions);
            newFile.name = file.name;
            file = newFile;
        }

        let ext = file.name.split('.').pop();

        const filename = (new Date()).getTime() + '.' + ext;
        uploadPath += filename;

        let formData = new FormData();
        formData.append('OSSAccessKeyId', uploadParameter.accessid);
        formData.append('policy', uploadParameter.policy);
        formData.append('Signature', uploadParameter.signature);
        formData.append('key', uploadParameter.dir + '/' + filename);
        formData.append('success_action_status', 200); // 指定返回的状态码
        formData.append('file', file, filename); // 填入文件

        await axios.post(uploadParameter.host, formData, ajaxOptions);

        let fileObj = {
            fileName: file.name,
            url: uploadParameter.host + '/' + uploadParameter.dir + '/' + filename,
        };

        if (file.type.includes('image') && ! file.type.includes('gif')) fileObj.url += '?x-oss-process=style/watermark';
        filesUrl.push(fileObj);
    }
    return filesUrl;
};
